package priv.conceit.sc.hoxton.file.util;

import cn.hutool.core.collection.CollUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * sc-hoxton pdf 工具
 *
 * @author Conceit
 * 2020/6/11 增加方法
 * @since 1.0.0, 2020/6/11
 */
public class PdfUtil {

	Document document =null;
	public  boolean generatePdf(File convertFile, String title, List<String> items) {

		try {
			//生成pdf
			document = new Document(PageSize.A4);
			PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(convertFile));

			BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			Font titleFont = new Font(bfChinese, 20, Font.BOLD);
			Font mainFont = new Font(bfChinese, 10, Font.NORMAL);

			document.open();
			/**
			 * 标题
			 */
			document.addTitle(title);
			Paragraph titleBody = new Paragraph();
			/**
			 * 行间距
			 */
			titleBody.setLeading(20f);
			/**
			 * 中
			 */
			titleBody.setAlignment(1);
			titleBody.setFont(titleFont);
			titleBody.add(title);
			titleBody.add(Chunk.NEWLINE);
			titleBody.add(new Chunk(new LineSeparator()));

			Paragraph mainBody = new Paragraph();
			mainBody.setFont(mainFont);
			/**
			 * 行间距
			 */
			mainBody.setLeading(15f);


			if(CollUtil.isNotEmpty(items)){
				for(String item:items){
					mainBody.add(Chunk.NEWLINE);
                    mainBody.add(item);
				}
			}

			mainBody.add(Chunk.NEWLINE);
			mainBody.add(new Chunk(new LineSeparator()));
			document.add(titleBody);
			document.add(mainBody);
		} catch (IOException | DocumentException e) {
			e.printStackTrace();
			cn.hutool.core.io.FileUtil.del(convertFile);
			return false;
		} finally {
			if(Objects.nonNull(document)){
				document.close();
			}
		}
		return true;

	}

}
